package com.nbcio.pm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.common.core.utils.MapstructUtils;
import com.nbcio.common.core.utils.StringUtils;
import com.nbcio.pm.domain.PmTeamProject;
import com.nbcio.pm.domain.PmTeamMember;
import com.nbcio.pm.domain.PmProjectMember;
import com.nbcio.pm.domain.bo.PmTeamProjectBo;
import com.nbcio.pm.domain.vo.PmTeamProjectVo;
import com.nbcio.pm.mapper.PmTeamProjectMapper;
import com.nbcio.pm.mapper.PmTeamMemberMapper;
import com.nbcio.pm.mapper.PmProjectMemberMapper;
import com.nbcio.pm.service.IPmTeamProjectService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 团队项目关联Service业务层处理
 *
 * @author nbacheng
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PmTeamProjectServiceImpl implements IPmTeamProjectService {

    private final PmTeamProjectMapper baseMapper;
    private final PmTeamMemberMapper teamMemberMapper;
    private final PmProjectMemberMapper projectMemberMapper;

    /**
     * 查询团队项目关联
     */
    @Override
    public PmTeamProjectVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询团队项目关联列表
     */
    @Override
    public TableDataInfo<PmTeamProjectVo> queryPageList(PmTeamProjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PmTeamProject> lqw = buildQueryWrapper(bo);
        Page<PmTeamProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询团队项目关联列表
     */
    @Override
    public List<PmTeamProjectVo> queryList(PmTeamProjectBo bo) {
        LambdaQueryWrapper<PmTeamProject> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 新增团队项目关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PmTeamProjectBo bo) {
        PmTeamProject add = MapstructUtils.convert(bo, PmTeamProject.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改团队项目关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(PmTeamProjectBo bo) {
        PmTeamProject update = MapstructUtils.convert(bo, PmTeamProject.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 校验并批量删除团队项目关联信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询团队参与的项目列表
     */
    @Override
    public List<PmTeamProjectVo> queryByTeamId(Long teamId) {
        PmTeamProjectBo queryBo = new PmTeamProjectBo();
        queryBo.setTeamId(teamId);
        return queryList(queryBo);
    }

    /**
     * 查询项目参与的团队列表
     */
    @Override
    public List<PmTeamProjectVo> queryByProjectId(Long projectId) {
        PmTeamProjectBo queryBo = new PmTeamProjectBo();
        queryBo.setProjectId(projectId);
        return queryList(queryBo);
    }

    /**
     * 关联团队到项目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean associateTeamToProject(Long teamId, Long projectId, Boolean isPrimary) {
        // 检查是否已经关联
        LambdaQueryWrapper<PmTeamProject> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeamProject::getTeamId, teamId)
           .eq(PmTeamProject::getProjectId, projectId);
        
        PmTeamProject existing = baseMapper.selectOne(lqw);
        if (existing != null) {
            log.warn("团队 {} 已经关联到项目 {}", teamId, projectId);
            return false;
        }

        // 创建关联
        PmTeamProject teamProject = new PmTeamProject();
        teamProject.setTeamId(teamId);
        teamProject.setProjectId(projectId);
        teamProject.setIsPrimary(isPrimary != null ? isPrimary : false);

        boolean flag = baseMapper.insert(teamProject) > 0;
        
        if (flag) {
            // 自动将团队成员添加到项目成员
            addTeamMembersToProject(teamId, projectId);
        }
        
        return flag;
    }

    /**
     * 取消团队与项目的关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean disassociateTeamFromProject(Long teamId, Long projectId) {
        LambdaQueryWrapper<PmTeamProject> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeamProject::getTeamId, teamId)
           .eq(PmTeamProject::getProjectId, projectId);
        
        PmTeamProject teamProject = baseMapper.selectOne(lqw);
        if (teamProject == null) {
            log.warn("团队 {} 与项目 {} 没有关联", teamId, projectId);
            return false;
        }

        // 先移除团队成员从项目成员
        removeTeamMembersFromProject(teamId, projectId);
        
        // 删除关联
        return baseMapper.deleteById(teamProject.getId()) > 0;
    }

    /**
     * 批量添加团队成员到项目
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addTeamMembersToProject(Long teamId, Long projectId) {
        // 查询团队成员
        LambdaQueryWrapper<PmTeamMember> teamMemberQuery = Wrappers.lambdaQuery();
        teamMemberQuery.eq(PmTeamMember::getTeamId, teamId)
                      .eq(PmTeamMember::getIsActive, true);
        
        List<PmTeamMember> teamMembers = teamMemberMapper.selectList(teamMemberQuery);
        
        int addedCount = 0;
        for (PmTeamMember teamMember : teamMembers) {
            // 检查是否已经是项目成员
            LambdaQueryWrapper<PmProjectMember> projectMemberQuery = Wrappers.lambdaQuery();
            projectMemberQuery.eq(PmProjectMember::getProjectId, projectId)
                             .eq(PmProjectMember::getUserId, teamMember.getUserId());
            
            PmProjectMember existingProjectMember = projectMemberMapper.selectOne(projectMemberQuery);
            if (existingProjectMember != null) {
                continue; // 已经是项目成员，跳过
            }

            // 添加为项目成员
            PmProjectMember projectMember = new PmProjectMember();
            projectMember.setProjectId(projectId);
            projectMember.setUserId(teamMember.getUserId());
            projectMember.setRole(convertTeamRoleToProjectRole(teamMember.getRoleId()));
            projectMember.setIsActive(true);
            projectMember.setStatus("1");
            
            if (projectMemberMapper.insert(projectMember) > 0) {
                addedCount++;
            }
        }
        
        log.info("团队 {} 的 {} 个成员已添加到项目 {}", teamId, addedCount, projectId);
        return addedCount > 0;
    }

    /**
     * 从项目移除团队成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeTeamMembersFromProject(Long teamId, Long projectId) {
        // 查询团队成员
        LambdaQueryWrapper<PmTeamMember> teamMemberQuery = Wrappers.lambdaQuery();
        teamMemberQuery.eq(PmTeamMember::getTeamId, teamId);
        
        List<PmTeamMember> teamMembers = teamMemberMapper.selectList(teamMemberQuery);
        
        int removedCount = 0;
        for (PmTeamMember teamMember : teamMembers) {
            // 从项目成员中移除
            LambdaQueryWrapper<PmProjectMember> projectMemberQuery = Wrappers.lambdaQuery();
            projectMemberQuery.eq(PmProjectMember::getProjectId, projectId)
                             .eq(PmProjectMember::getUserId, teamMember.getUserId());
            
            if (projectMemberMapper.delete(projectMemberQuery) > 0) {
                removedCount++;
            }
        }
        
        log.info("团队 {} 的 {} 个成员已从项目 {} 移除", teamId, removedCount, projectId);
        return removedCount > 0;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<PmTeamProject> buildQueryWrapper(PmTeamProjectBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PmTeamProject> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTeamId() != null, PmTeamProject::getTeamId, bo.getTeamId());
        lqw.eq(bo.getProjectId() != null, PmTeamProject::getProjectId, bo.getProjectId());
        lqw.eq(bo.getIsPrimary() != null, PmTeamProject::getIsPrimary, bo.getIsPrimary());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                PmTeamProject::getCreateTime, params.get("beginTime"), params.get("endTime"));
        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmTeamProject entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 将团队角色转换为项目角色
     */
    private String convertTeamRoleToProjectRole(Long teamRoleId) {
        // 这里可以根据实际的角色映射关系进行转换
        // 暂时使用简单的映射
        if (teamRoleId == null) {
            return "developer";
        }
        
        // 可以根据团队角色ID映射到项目角色
        // 这里需要根据实际的团队角色定义来调整
        switch (teamRoleId.intValue()) {
            case 1: // 项目经理
                return "manager";
            case 2: // 技术负责人
                return "tech_lead";
            case 3: // 开发人员
                return "developer";
            case 4: // 测试人员
                return "tester";
            case 5: // 产品经理
                return "product_manager";
            case 6: // UI设计师
                return "ui_designer";
            case 7: // 运维人员
                return "devops";
            case 8: // 观察者
                return "observer";
            default:
                return "developer";
        }
    }
}
